package com.groupbuying.redpacket.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.groupbuying.redpacket.config.CustomerMQConfig;
import com.groupbuying.redpacket.constants.CommonConstants;
import com.groupbuying.redpacket.constants.CustomerEnum;
import com.groupbuying.redpacket.constants.RedisConstans;
import com.groupbuying.redpacket.dao.CustomerDao;
import com.groupbuying.redpacket.domain.CustomerDO;
import com.groupbuying.redpacket.domain.UserToken;
import com.groupbuying.redpacket.service.CustomerService;
import com.groupbuying.redpacket.utils.JwtUtils;
import com.groupbuying.redpacket.utils.MD5Utils;
import com.groupbuying.redpacket.utils.RedisUtils;
import com.groupbuying.redpacket.utils.SmsUtils;
import com.groupbuying.redpacket.utils.apiresult.ApiResult;
import com.groupbuying.redpacket.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: mayunfei
 * @Date: Create in 10:07 2019/11/22
 * @tar:
 */
@Service
public class CustomerLoginServiceImpl implements CustomerService {
    private Logger log = LoggerFactory.getLogger(CustomerLoginServiceImpl.class);

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private Producer producer;


    /**
     * 账号密码登录
     */
    @Override
    public ApiResult login(Map<String, Object> params) {
        Object tempParam = params.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        tempParam = params.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            log.error("传入参数为空");
            return ApiResult.paramIsNull();
        }

        List<CustomerDO> customers = customerDao.getCustomerByMobile(mobile);
        if(customers.size() == 0){

            return ApiResult.failure(ApiResultCode.LOGINPHONENOTEXISTS, "");
        }
        CustomerDO customer = customers.get(0);
        //检测会员是否冻结
        if (CustomerEnum.CUSTOMER_FROZENSTATE_FROZEN.equals(customer.getFrozenstate())) {
            // 如果会员已经冻结，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERFROZEN, "");
        }
        //检测会员是否激活
        if (CustomerEnum.CUSTOMER_ACTIVESTATE_UNACTIVATE.equals(customer.getActivestate())) {
            // 如果会员未激活，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERNOACTIVATION, "");
        }
        Map result = new HashMap();
        try {
            if (StringUtils.isEmpty(customer.getPassword())) {
                log.error("customer用户:{},密码为空", customer);
                return ApiResult.failure(ApiResultCode.PASSWORDERROR, "");
            }
            if (!customer.getPassword().equals(MD5Utils.md5(password))) {
                log.error("customer用户:{},密码不一致", customer);
                return ApiResult.failure(ApiResultCode.PASSWORDERROR, "");
            }
            UserToken userToken = new UserToken(customer.getMobile(), customer.getUuid(), "");
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);
            result.put("mobile", mobile);
            log.info("用户：{},登录成功，token:{}", userToken);
            return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
        } catch (Exception e) {
            return ApiResult.failure(ApiResultCode.FAILURE);
        }
    }

    /**
     * 手机号验证码登录
     */
    @Override
    public ApiResult verificationCodeLogin(Map<String, Object> map) throws Exception {
        Object tempParam = map.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        tempParam = map.get("code");
        //验证码
        String identifyingCode = tempParam == null ? null : tempParam.toString();
        if (StringUtils.isEmpty(mobile)) {
            log.error("传入手机号为空");
            return ApiResult.paramIsNull();
        }
        if (StringUtils.isEmpty(identifyingCode)) {
            log.error("传入验证码为空");
            return ApiResult.paramIsNull();
        }
        //获取redis的验证码
        String value = (String) redisUtils.getValue(RedisConstans.RED_PACKAGE_CODE + mobile);
        //验证码不相等
        if (!identifyingCode.equals(value)) {
            log.error("密码不一致");
            return ApiResult.failure(ApiResultCode.VERIFICATIONCODEERROR, "");
        }


        List<CustomerDO> customers = customerDao.getCustomerByMobile(mobile);
        if(customers.size() == 0){
            return ApiResult.failure(ApiResultCode.LOGINPHONENOTEXISTS,"");
        }
        CustomerDO customer = customers.get(0);
        //检测会员是否冻结
        if (CustomerEnum.CUSTOMER_FROZENSTATE_FROZEN.equals(customer.getFrozenstate())) {
            // 如果会员已经冻结，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERFROZEN, "");
        }
        //检测会员是否激活
        if (CustomerEnum.CUSTOMER_ACTIVESTATE_UNACTIVATE.equals(customer.getActivestate())) {
            // 如果会员未激活，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERNOACTIVATION, "");
        }
        try {
            Map result = new HashMap();
            UserToken userToken = new UserToken(customer.getMobile(), customer.getUuid(), "");
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);
            result.put("mobile", mobile);
            log.info("登录成功");
            return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
        } catch (Exception e) {
            log.error("登录失败");
            return ApiResult.failure(ApiResultCode.FAILURE);
        }
    }

    /**
     * 验证码
     */
    @Override
    public ApiResult identifyingCode(Map<String, Object> map) {
        Object tempParam = map.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        if (StringUtils.isEmpty(mobile)) {
            log.error("手机号为空");
            return ApiResult.paramIsNull();
        }
        if (redisUtils.isHasKey(RedisConstans.RED_PACKAGE_CODE + mobile)){
            return ApiResult.failure(ApiResultCode.REAPEATREQUEST,"");
        }

        List<CustomerDO> customers = customerDao.getCustomerByMobile(mobile);
        if(customers.size() == 0){
            return ApiResult.failure(ApiResultCode.LOGINPHONENOTEXISTS,"");
   }
        CustomerDO customer = customers.get(0);
        //检测会员是否冻结
        if (CustomerEnum.CUSTOMER_FROZENSTATE_FROZEN.equals(customer.getFrozenstate())) {
            // 如果会员已经冻结，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERFROZEN, "");
        }
        //检测会员是否激活
        if (CustomerEnum.CUSTOMER_ACTIVESTATE_UNACTIVATE.equals(customer.getActivestate())) {
            // 如果会员未激活，则返回提示
            return ApiResult.failure(ApiResultCode.CUSTOMERNOACTIVATION, "");
        }
        String code = "";
        for (int i = 0; i < 4; i++) {
            int x = (int) (Math.random() * 10);
            code += x;
        }
        try {
            redisUtils.setKey(RedisConstans.RED_PACKAGE_CODE + mobile, code, 60L);
            //发送验证码
            boolean sendResult = SmsUtils.sendCodeForRegister(mobile, code);
            if (sendResult) {
                log.info("验证码发送成功");
                return ApiResult.success(ApiResultCode.SUCCESS_GETCODE, "");
            }
            return ApiResult.failure(ApiResultCode.SENDCODEFAILURE, "");
        } catch (Exception e) {
            log.error("验证码发送失败");
            return ApiResult.failure(ApiResultCode.SENDCODEFAILURE, "");
        }

    }

}
